<?php
/**
 * @特惠赚、用户控制器User
 * $apisign=I('server.HTTP_APISIGN','',trim);
 * Author: 小谢
 * Date: 2019-5-13
 */
namespace app\api\controller;
use app\api\logic\SendSmsLogic;
use think\Db;
use think\facade\Cache;
use app\api\model\User as UserModel;

class User extends Base
{

    /**
    *@brief 手机登陆接口
    */
    public function login() {
        $mobile   = I('get.mobile');//手机号码
        $password = I('get.password/s');//密码

        //手机验证、密码验证
        $validate = new \app\api\validate\User();
        $data = ['mobile'=>$mobile,'password'=>$password];
        if (!$validate->check($data)){
            $error_info = explode(":",$validate->getError());
            $this->ajaxReturn($this->callBack(intval($error_info[0]),0,$error_info[1],self::emptyObject()),'JSON');
        }

        $UserModel = new UserModel();
        $return = $UserModel->getUserInfo($data);
        if($return['status'] == 1) {
            $token = $this->setToken();//获取token
            $condition = ['user_id'=>$return['user_id']];
            //更新token
            $res = M('user_token')->where($condition)->update(['token'=>$token,'time_out'=>time() + 604800]);
            if($res) {
                $this->ajaxReturn($this->callBack(1,0,'登陆成功',['token'=>$token]),'JSON');
            }
        }
        $this->ajaxReturn($this->callBack(0,0,'账户或者密码错误',self::emptyObject()),'JSON');
    }

    /**
     * @brief 微信登录
     */
    public function wechatLogin() {
        $post = I('get.');
        if(empty($post['openid'])) {
            $this->ajaxReturn($this->callBack(0,0,'openid不能为空',self::emptyObject()),'JSON');
        }
        $condition['openid'] = $post['openid'];
        $user = M('user')->where($condition)->find();
        if(isset($user)) {
            $token = $this->setToken();//获取token
            $where = ['user_id'=>$user['user_id']];
            $res = M('user_token')->where($where)->update(['token'=>$token,'time_out'=>time() + 604800]);
            if($res) {
                $this->ajaxReturn($this->callBack(1,0,'登陆成功',['token'=>$token]),'JSON');
            }
        }
        $this->ajaxReturn($this->callBack(0,0,'登陆失败',self::emptyObject()),'JSON');
    }


    /**
     * @brief 用户注册
     */
    public function register() {
        $mobile    = I('post.mobile');//手机号码
        $password  = I('post.password');//密码
        $code      = I('post.code'); //手机验证码
        $invite_id = I('post.invite_id');//邀请ID
        
        if(I('post.')) {
            //获取缓存里手机验证、校验验证码
            $cache_code = Cache::store('redis')->get('code_'.$mobile);
            if(!$cache_code) {
                $this->ajaxReturn($this->callBack(0,0,'验证码已过期',self::emptyObject()),'JSON');
            } else if($cache_code != $code) {
                $this->ajaxReturn($this->callBack(0,0,'验证码错误',self::emptyObject()),'JSON');
            }
            //查询手机号码是否被注册
            $user = M('user')->where(['mobile'=>$mobile])->column('mobile');

            if($user) {
                $this->ajaxReturn($this->callBack(0,0,'手机号已被注册',self::emptyObject()),'JSON');
            }
            $fields = ['user_id,super_ids'];
            $row = M('user')->where(['user_id'=>$invite_id])->field($fields)->find();
            $data = [
                "mobile"=>$mobile,
                "password"=> md5($password),
                "super_ids"=>$row['super_ids'].'|'.$row['user_id'].'|',
                "agentid"=>$row['user_id'],
                "reg_time"=>time()
            ];
            $token = $this->setToken();//获取token
            $user_id = Db::name('User')->insertGetId($data);
            if($user_id) {
                //保存token
                $res = M('user_token')->add(['token'=>$token,'time_out'=>time() + 604800,'user_id'=>$user_id]);
                if($res) {
                   M('user_info')->add(['user_id'=>$user_id]);//用户详细资料表
                   $this->ajaxReturn($this->callBack(0,0,'注册成功',['token'=>$token]),'JSON');
                }
            }
        }
        $this->ajaxReturn($this->callBack(0,0,'注册失败',self::emptyObject()),'JSON');
    }

    /**
     * @brief 查找邀请人
     */
    public function invite() {
        $invite_id = I('post.invite_id');//邀请ID
        if(!is_numeric($invite_id)) {
            $this->ajaxReturn($this->callBack(0,0,'请输入正确邀请ID',self::emptyObject()),'JSON');
        }
        //查找邀请ID对应用户信息
        $condition = ['user_id'=>$invite_id];
        $row = M('user')->where($condition)->field(['username,head_ico'])->find();
        if($row) {
            $this->ajaxReturn($this->callBack(1,0,'获取成功',$row),'JSON');
        }
        $this->ajaxReturn($this->callBack(0,0,'获取邀请人信息失败',self::emptyObject()),'JSON');
    }

    /**
     * @brief 绑定微信
     */
    public function bingWechat() {
        $post = I('post.');
        //验证token
        $return = $this->checkToken($post['token']);
        if($return['status'] == 0) {
            $this->ajaxReturn($return,'JSON');
        }
        $data = [
            "openid"=>$post['openid'],//openid
            "username"=>$post['username'],//用户昵称
            "head_ico"=>$post['head_ico'],//头像
            "gender"=>$post['gender'],//性别
            "is_auth"=>1,//状态修改为授权
        ];
        $condition = ['user_id'=>$return['user_id']];
        $user = M('user')->where($condition)->update($data);
        if($user) {
            $this->ajaxReturn($this->callBack(1,0,'绑定成功',self::emptyObject()),'JSON');
        }
        $this->ajaxReturn($this->callBack(0,0,'绑定失败',self::emptyObject()),'JSON');
    }

    /**
     * @brief 微信是否授权
     */
    public function isAuth() {
        $post = I('get.');
        if(empty($post['openid'])) {
            $this->ajaxReturn($this->callBack(0,0,'openid不能为空',self::emptyObject()),'JSON');
        }
        $condition['openid'] = $post['openid'];
        $user = M('user')->where($condition)->column('is_auth');
        if($user[0] == 1) {
            $this->ajaxReturn($this->callBack(1,0,'已授权',self::emptyObject()),'JSON');
        }
        $this->ajaxReturn($this->callBack(0,0,'未授权',self::emptyObject()),'JSON');
    }

    /**
     * @brief 发送短信验证码
     */
    public function getSmsCode() {
        $mobile = I('post.');
        if(empty($mobile)) {
            $this->ajaxReturn($this->callBack(0,0,'请输入手机号码',self::emptyObject()),'JSON');
        }
        $rand_code = rand(100000,999999);//随机验证码
        Cache::store('redis')->set('code_'.$mobile,$rand_code,60);//保存手机验证码到缓存里、有效时间设置60秒
        $SendSmsLogic = new SendSmsLogic();
        $result = $SendSmsLogic->_exe($mobile,$rand_code);
        $output = json_decode($result,true);
        if(isset($output['code'])  && $output['code']=='0'){
            $this->ajaxReturn($this->callBack(1,0,'发送成功',self::emptyObject()),'JSON');
        } 
        $this->ajaxReturn($this->callBack(0,0,'发送失败',self::emptyObject()),'JSON');
    }

}
